/**
 * 
 */
package org.statewalker.parser.wiki.tokenizer.block;

import org.statewalker.parser.wiki.grammar.WikiBlockDict;
import org.statewalker.tokenizer.CharStream;
import org.statewalker.tokenizer.ITokenizer;
import org.statewalker.tokenizer.StreamToken;
import org.statewalker.tokenizer.CharStream.Marker;

public class HeaderBeginTokenizer implements ITokenizer {

    private String[] fKeys;

    public HeaderBeginTokenizer() {
        this(
            WikiBlockDict.H1,
            WikiBlockDict.H2,
            WikiBlockDict.H3,
            WikiBlockDict.H4,
            WikiBlockDict.H5,
            WikiBlockDict.H6);
    }

    public HeaderBeginTokenizer(String... key) {
        super();
        fKeys = key;
    }

    protected boolean checkChar(char ch) {
        return ch == '=';
    }

    public StreamToken read(CharStream stream) {
        if (!checkChar(stream.getChar()))
            return null;
        StreamToken result = null;
        Marker marker = stream.markPosition();
        int counter = 0;
        try {
            while (counter < fKeys.length) {
                counter++;
                if (!stream.incPos())
                    break;
                if (!checkChar(stream.getChar()))
                    break;
            }
            if (counter > 0) {
                result = new StreamToken(fKeys[counter - 1], marker
                    .getPointer(), stream.getPointer(), marker.getSubstring());
            }
            return result;
        } finally {
            marker.close(result == null);
        }
    }
}